﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Web.Services;
using System.Text;
using System.Configuration;
using Catering.View_Operaction;

namespace Catering.Catering_Page.Caipin
{
    public partial class shippu_regth : UserIsNull
    {
        public DataTable dt_FoodMealType = new DataTable();
        public DataTable dt_AutoRecipe = new DataTable();
        public DataTable dt_RawMaterialsType = new DataTable();
        public DataTable dt_NElements = new DataTable();//存放元素列表
        public int m_Daycount = 0;

        public Hashtable WeekDatetime;
        public string[] strWeek = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
        public string[] strWeekByCh = new string[] { "一", "二", "三", "四", "五", "六", "日" };

        protected void Page_Load(object sender, EventArgs e)
        {
            this.HidTypeInfo1.Value = ConfigurationManager.AppSettings["TypeInfo1"].ToString();
            this.HidTypeInfo2.Value = ConfigurationManager.AppSettings["TypeInfo2"].ToString();
            this.HidTypeInfo3.Value = ConfigurationManager.AppSettings["TypeInfo3"].ToString();
            if (dt_NElements.Rows.Count<=0)
            {
                this.dt_NElements = new Catering_Rules.NutritionElements().GetAllList().Tables[0];
            }
  

            if (!IsPostBack)
            {
                if (Request.QueryString["cid"] != null)
                {
                    //绑定周期Dr_zhoulist
                    DataTable dt_Week = new Catering_Rules.T_RecipesWeek().GetList(100, "RecipesID=" + Request.QueryString["cid"].ToString(), "Number").Tables[0];
                    this.Dr_zhoulist.LoadDrop(dt_Week, "id", "temp1");
                    this.HidWeekValue.Value = this.Dr_zhoulist.SelectedValue;
                }

                this.LoadData();
                this.LoadRecipes();
                this.LoadRep();
            }
        }

        protected void LoadRep()
        {
            DataTable dt_Recipes = new DataTable();
            if (Session["RoleID"] != null)
            {
                int roleid = 0;
                Int32.TryParse(Session["RoleID"].ToString(), out roleid);
                if (roleid > 0)
                {
                    Catering_Model.Role temprole = new Catering_Rules.Role().GetModel(roleid);
                    if (temprole != null && temprole.RoleName == "管理员")
                    {
                        dt_Recipes = new Catering_Rules.T_Recipes().GetAllList().Tables[0];
                    }
                    else
                    {
                        if (Session["ClassID"] != null)
                        {
                            int classid = 0;
                            Int32.TryParse(Session["ClassID"].ToString(), out classid);
                            if (classid > 0)
                            {
                                dt_Recipes = new Catering_Rules.T_Recipes().GetList(" ClassID=" + classid
                                    + " OR (ClassID IN(SELECT ClassID FROM View_CompanyClass WHERE "
                                + " CompanyID=(SELECT TOP 1 CompanyID FROM View_CompanyClass WHERE ClassID="
                                + classid + ")) AND IsBiaoZhun=1 )").Tables[0];
                            }
                        }
                    }
                }
            }
            this.Rep_shipuList.DataSource = dt_Recipes;
            this.Rep_shipuList.DataBind();
        }

        //初始化dt容器
        private void dt_Init()
        {
            DataTable dt_Recipes = new DataTable();
            dt_Recipes.Columns.Add("Date");//日期
            dt_Recipes.Columns.Add("CID");//菜
            dt_Recipes.Columns.Add("FMID");//餐别
            dt_Recipes.Columns.Add("RandomId");//随机ID

            DataTable dt_RecipesInfo = new DataTable();
            dt_RecipesInfo.Columns.Add("RandomId");
            dt_RecipesInfo.Columns.Add("RawID");
            dt_RecipesInfo.Columns.Add("Number");
            dt_RecipesInfo.Columns.Add("RAWZS");

            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;
        }

        protected void LoadData()
        {
            this.dt_Init();

            //餐别列表
            this.dt_FoodMealType = new Catering_Rules.FoodMealType().GetList("1=1 order by temp1").Tables[0];
            //生成食谱默认数据
            this.dt_AutoRecipe = new Catering_Rules.AutoRecipe().GetAllList().Tables[0];
            //食物种属
            this.dt_RawMaterialsType = new Catering_Rules.RawMaterialsType().GetAllList().Tables[0];

            if (this.Dr_zhoulist.SelectedItem != null)
            {
                Catering_Model.E_RecipesWeek md_week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.Dr_zhoulist.SelectedValue));
                this.HidDayCount.Value = ((md_week.endDate - md_week.startDate).Days + 1).ToString();//提取本周天数
            }
            else
            {
                this.HidDayCount.Value = "0";
            }

            this.LoadDt();
        }

        //填充食谱详细
        public void LoadDt()
        {
            if (this.Dr_zhoulist.Items.Count == 0)
                return;

            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            Catering_Model.E_RecipesWeek md = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.Dr_zhoulist.SelectedValue));
            string strWhere = "MID=" + Convert.ToInt32(Request.QueryString["cid"]) + " and Date>=convert(datetime,'" + md.startDate.ToShortDateString() + "') and Date<=convert(datetime,'" + md.endDate.ToShortDateString() + "') ";
            DataTable dt_Recipeinfo = new Catering_Rules.T_RecipeInformation().GetList(strWhere).Tables[0];

            if (dt_Recipeinfo != null && dt_Recipeinfo.Rows.Count > 0)
            {
                Random rd = new Random();
                for (int i = 0; i < dt_Recipeinfo.Rows.Count; i++)
                {
                    string strRandomId = Guid.NewGuid().ToString();//rd.Next(100000).ToString();
                    DataRow row = dt_Recipes.NewRow();
                    row["Date"] = Convert.ToDateTime(dt_Recipeinfo.Rows[i]["Date"].ToString()).ToShortDateString();
                    row["CID"] = dt_Recipeinfo.Rows[i]["CID"].ToString();
                    row["FMID"] = dt_Recipeinfo.Rows[i]["FMID"].ToString();
                    row["RandomID"] = "div_" + strRandomId;
                    dt_Recipes.Rows.Add(row);

                    DataTable dt_RecipeinfoInfo = new Catering_Rules.T_RecipeInformationInfo().GetList("RecipeInformationID=" + dt_Recipeinfo.Rows[i]["id"].ToString()).Tables[0];
                    foreach (DataRow rows in dt_RecipeinfoInfo.Rows)
                    {
                        DataRow rowinfo = dt_RecipesInfo.NewRow();
                        rowinfo["RandomID"] = row["RandomID"].ToString();
                        rowinfo["RawID"] = rows["RawID"].ToString();
                        rowinfo["Number"] = rows["Number"].ToString();
                        Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(rows["RawID"].ToString()));
                        rowinfo["RAWZS"] = md_Raw == null ? "-1" : md_Raw.RAWZS.ToString();
                        dt_RecipesInfo.Rows.Add(rowinfo);
                    }
                }
            }

            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;
        }

        //加载食谱信息
        protected void LoadRecipes()
        {
            if (Request.QueryString["cid"] == null)
            {
                this.but_Save.Enabled = false;
                return;
            }

            this.Hidshipuid.Value = Request.QueryString["cid"].ToString();
            Catering_Model.E_Recipes md_Recipes = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(Request.QueryString["cid"]));

            this.lbName.Text = md_Recipes.CateringName;
            if (md_Recipes.ClassIDs != 0)
            {
                this.lblClass.Text = new Catering_Rules.ClassInfo().GetModel(md_Recipes.ClassIDs).CName;
            }
            this.lblNumber.Text = md_Recipes.Number.ToString() == "0" ? "1" : md_Recipes.Number.ToString();

            DataTable dt_pingjia = new Catering_Rules.FoodMealEvaluation().GetList("FMID=" + Convert.ToInt32(Request.QueryString["cid"])).Tables[0];
            if (dt_pingjia != null && dt_pingjia.Rows.Count > 0)
            {
                this.txt_jinji.Text = dt_pingjia.Rows[0]["Economic"].ToString();
                this.txt_yingyang.Text = dt_pingjia.Rows[0]["Nutrition"].ToString();
            }

            //通过时间段 绑定周期
            this.Dr_zhoulist_SelectedIndexChanged(null, null);

            //绑定标准摄入量
            this.LoadSRliang();
        }

        //绑定星期对应的日期
        protected void WeekBing()
        {
            Catering_Model.E_RecipesWeek md_Week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.Dr_zhoulist.SelectedValue));
            this.WeekDatetime = new Hashtable();
            for (DateTime time = md_Week.startDate; time <= md_Week.endDate; time = time.AddDays(1))
            {
                switch (time.DayOfWeek)
                {
                    case DayOfWeek.Friday:
                        this.WeekDatetime.Add("Friday", time.ToShortDateString());//星期五
                        break;
                    case DayOfWeek.Monday:
                        this.WeekDatetime.Add("Monday", time.ToShortDateString());//星期一
                        break;
                    case DayOfWeek.Saturday:
                        this.WeekDatetime.Add("Saturday", time.ToShortDateString());//星期六
                        break;
                    case DayOfWeek.Sunday:
                        this.WeekDatetime.Add("Sunday", time.ToShortDateString());//星期日
                        break;
                    case DayOfWeek.Thursday:
                        this.WeekDatetime.Add("Thursday", time.ToShortDateString());//星期四
                        break;
                    case DayOfWeek.Tuesday:
                        this.WeekDatetime.Add("Tuesday", time.ToShortDateString());//星期二
                        break;
                    case DayOfWeek.Wednesday:
                        this.WeekDatetime.Add("Wednesday", time.ToShortDateString());//星期三
                        break;
                }
            }
        }

        //添加菜品
        protected void But_AddDish_Click(object sender, EventArgs e)
        {
            string str = this.Hid_AddDish.Value;
            string cid = str.Split('|')[0].ToString();
            string date = str.Split('|')[1].ToString();
            string FoodID = str.Split('|')[2].ToString();
            string strRandomNum = "div_" + Guid.NewGuid().ToString();
            this.Edit_Recipes(cid, date, FoodID, strRandomNum, "Add");
            string result = this.GetCaiHtmlByData(cid, strRandomNum, FoodID, date,false,false);
            if (result.Contains('<'))
            {
                ScriptManager.RegisterStartupScript(
                    this.UpdatePanel1,
                    this.UpdatePanel1.GetType(),
                    Guid.NewGuid().ToString(),
                    "$(document).ready(function () {Dish_Add('" + result + "','" + date + "','" + FoodID + "');});",
                    true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(
                    this.UpdatePanel1,
                    this.UpdatePanel1.GetType(),
                    Guid.NewGuid().ToString(),
                    "alert('" + result + "');",
                    true);
            }
        }

        public string GetCaiHtmlByData(string cid, string strRandomNum, string FoodID, string date, bool HaveNone, bool IsAll = false)
        {
            string result = this.GetCaiHtmlByData(cid, strRandomNum, FoodID, date);
            if (result.Contains('<'))
            {
                return result;
            }
            else if (HaveNone)
            {
                return "";
            }
            else
            {
                return result;
            }
        }

        //获取实际菜原料用量信息
        public string GetCaiHtmlByData(string cid, string strRandomNum, string FoodID, string date, bool IsAll = false)
        {
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            //菜信息
            System.Text.StringBuilder stsb = new System.Text.StringBuilder();
            Catering_Model.E_Dish md = new Catering_Rules.T_Dish().GetModel(Convert.ToInt32(cid));
            if (md == null)
                return "";
            stsb.Append("<tr id=\"" + strRandomNum + "\" Is_tzcai=\"true\"><td width=\"50%\" style=\"padding:0px;\">");
            stsb.Append("<div style=\"text-align: left; display:block;cursor: pointer\" " + (IsAll ? "IsCunZai=\"false\"" : "IsCunZai=\"true\"") + " FoodID=\"" + FoodID + "\" date=\"" + date + "\" TypeID=\"" + md.DTID.ToString() + "\" class=\"pgridadivss\" cid=\"" + cid + "\"   >");
            stsb.Append("<span style=\"float: left; margin-left: 5px\" class=\"pgridalabel\">" + md.Name + "</span>");
            stsb.Append("</div>");
            stsb.Append("</td><td width=\"50%\" style=\"padding:0px;\">");

            //原料信息
            stsb.Append("<div style=\"margin-top: 4px; cursor: pointer;\" cid=\"" + cid + "\" >");

            Catering_Model.E_Recipes md_Recipes = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(Request.QueryString["cid"]));
            Catering_Model.ClassInfo md_Class=new Catering_Rules.ClassInfo().GetModel(md_Recipes.ClassID);

            foreach (DataRow row in dt_RecipesInfo.Select("RandomID='" + strRandomNum + "'"))
            {
                Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(row["RawID"].ToString()));
                if (md_Raw != null)
                {
                    bool canadd = CanBeAdd(md_Raw, md_Class.AreaID);
                    string RawName = md_Raw.RAWName;
                    if (md_Class.CName != "自营公司" && !canadd) return "您所在的配送区域不存在该菜品的原料“" + md_Raw.RAWName + "”！";
                    stsb.Append("<div style=\"width: 100%; white-space: nowrap; height: 18px\" >");
                    stsb.Append("<span style=\"float: left; margin-left: 5px\" class=\"pgridblabel\" >" + RawName + "</span>");
                    stsb.Append("<span style=\"float: right; margin-right: 5px;\" isNumber=\"true\" Randomid=\"" + strRandomNum + "\" Rawid=\"" + row["RawID"].ToString() + "\">" + Math.Round(Convert.ToDecimal(row["Number"].ToString())).ToString() + "</span>");
                    stsb.Append("</div>");
                }
            }
            stsb.Append("</div ></td></tr>");
            return stsb.ToString();
        }

        public bool CanBeAdd(Catering_Model.E_RawMaterial md_Raw, int area)
        {
            DataTable dt = null;
            switch (area)
            {
                case 2:
                    dt = new Catering_Rules.RawMaterial_Area().GetList(" InDBid LIKE '2%' and RawID=" + md_Raw.id + " ").Tables[0];
                    break;
                case 1:
                    dt = new Catering_Rules.RawMaterial_Area().GetList(" InDBid LIKE '1%' and RawID=" + md_Raw.id + " ").Tables[0];
                    break;
                case 3:
                    dt = new Catering_Rules.RawMaterial_Area().GetList(" InDBid LIKE '3%' and RawID=" + md_Raw.id + " ").Tables[0];
                    break;
                case 4:
                    dt = new Catering_Rules.RawMaterial_Area().GetList(" InDBid LIKE '4%' and RawID=" + md_Raw.id + " ").Tables[0];
                    break;
            }
            if (dt != null && dt.Rows.Count > 0) return true;
            return false;
        }

        //调整食谱详细数组-添加菜品
        public void Edit_Recipes(string CID, string Date, string Foodid, string RandomId, string command)
        {
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            DataRow row = dt_Recipes.NewRow();
            row["Date"] = Date;
            row["CID"] = CID;
            row["FMID"] = Foodid;
            row["RandomID"] = RandomId;
            dt_Recipes.Rows.Add(row);

            //需要保存菜用量详细
            DataTable dt = new Catering_Rules.T_DishInfo().GetList("DID=" + CID).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow rows in dt.Rows)
                {
                    Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(rows["RawID"].ToString()));
                    if (md_Raw != null)
                    {
                        DataRow rowinfo = dt_RecipesInfo.NewRow();
                        rowinfo["RandomID"] = RandomId;
                        rowinfo["RawID"] = rows["RawID"].ToString();
                        rowinfo["Number"] = rows["Content"].ToString();
                        rowinfo["RAWZS"] = md_Raw.RAWZS.ToString();
                        dt_RecipesInfo.Rows.Add(rowinfo);
                    }
                }
            }

            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;
        }

        //删除对应菜品
        protected void But_DelDish_Click(object sender, EventArgs e)
        {
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            string RandomID = this.Hid_DelDish.Value;

            if (dt_Recipes.Select("RandomID='" + RandomID + "'").Count() > 0)
            {
                dt_Recipes.Select("RandomID='" + RandomID + "'")[0].Delete();
                foreach (DataRow row in dt_RecipesInfo.Select("RandomID='" + RandomID + "'"))
                {
                    dt_RecipesInfo.Rows.Remove(row);
                }
            }

            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;

            ScriptManager.RegisterStartupScript(
                this.UpdatePanel1,
                this.UpdatePanel1.GetType(),
                Guid.NewGuid().ToString(),
                "$(document).ready(function () {fu_DelDish();});",
                true);

        }

        //调整原料用量
        protected void But_SetRawNumber_Click(object sender, EventArgs e)
        {
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            string str = this.Hid_SetRawNumber.Value;
            string RandomID = str.Split('|')[0].ToString();
            string RawID = str.Split('|')[1].ToString();
            string Number = str.Split('|')[2].ToString();
            dt_RecipesInfo.Select("RandomID='" + RandomID + "' and RawID='" + RawID + "'")[0]["Number"] = Number;

            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;

            ScriptManager.RegisterStartupScript(
                this.UpdatePanel1,
                this.UpdatePanel1.GetType(),
                Guid.NewGuid().ToString(),
                "$(document).ready(function () {fu_SetNumber('" + RandomID + "','" + RawID + "','" + Number + "');});",
                true);
        }

        //保存食谱
        protected void but_Save_Click(object sender, EventArgs e)
        {
            this.Save_Recipes();
            string CID = this.Hidshipuid.Value;
            if (Request.QueryString["IsNew"] != null && Request.QueryString["IsNew"].ToString()=="true")
            {
                CID = Request.QueryString["cid"].ToString();
            }
            Catering_Model.E_Recipes md = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(CID));
            if (md.GroupID != 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！');window.location='shippu_regth.aspx?cid=" + CID + "&IsGroupCatering=true&Edit=true'</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！');window.location='shippu_regth.aspx?cid=" + CID + "&Edit=true'</script>");
            }
            //this.but_input_Click(null, null);
        }

        public void Save_Recipes()
        {
            new Catering_Rules.FoodMealEvaluation().DeleteListBywhere("FMID=" + Request.QueryString["cid"]);
            //保存食谱评价
            Catering_Model.FoodMealEvaluation md_FoodMealEvaluation = new Catering_Model.FoodMealEvaluation();
            md_FoodMealEvaluation.FMID = Convert.ToInt32(Request.QueryString["cid"]);
            md_FoodMealEvaluation.Economic = this.txt_jinji.Text.Trim();
            md_FoodMealEvaluation.Nutrition = this.txt_yingyang.Text.Trim();
            md_FoodMealEvaluation.Date = DateTime.Now;
            md_FoodMealEvaluation.id = new Catering_Rules.FoodMealEvaluation().GetMaxId();
            new Catering_Rules.FoodMealEvaluation().Add(md_FoodMealEvaluation);

            Catering_Model.E_RecipesWeek md_week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.HidWeekValue.Value));
            string strDelWhere = "MID=" + Request.QueryString["cid"].ToString() + " and Date>=convert(datetime,'" + md_week.startDate.ToShortDateString() + "') and Date <=convert(datetime,'" + md_week.endDate.ToShortDateString() + "')";
            DataTable dt_RecipeInformation = new Catering_Rules.T_RecipeInformation().GetList(strDelWhere).Tables[0];
            foreach (DataRow row_RecipeInformation in dt_RecipeInformation.Rows)
            {
                new Catering_Rules.T_RecipeInformationInfo().DeleteListBywhere("RecipeInformationID=" + row_RecipeInformation["id"].ToString());
            }
            new Catering_Rules.T_RecipeInformation().DeleteList(strDelWhere);

            //保存食谱详细
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            if (dt_Recipes != null && dt_Recipes.Rows.Count > 0)
            {
                for (int i = 0; i < dt_Recipes.Rows.Count; i++)
                {
                    Catering_Model.E_RecipeInformation md_Recipeinfo = new Catering_Model.E_RecipeInformation();
                    md_Recipeinfo.FMID = Convert.ToInt32(dt_Recipes.Rows[i]["FMID"].ToString());
                    md_Recipeinfo.Date = Convert.ToDateTime(dt_Recipes.Rows[i]["Date"].ToString());
                    md_Recipeinfo.CID = Convert.ToInt32(dt_Recipes.Rows[i]["CID"].ToString());
                    md_Recipeinfo.MID = Convert.ToInt32(Request.QueryString["cid"]);
                    md_Recipeinfo.Week = this.GetWeekInt(Convert.ToDateTime(dt_Recipes.Rows[i]["Date"].ToString()).DayOfWeek);
                    int NoWeek = 0;
                    NoWeek = new Catering_Rules.T_RecipesWeek().GetNumber(md_Recipeinfo.Date, md_Recipeinfo.MID);
                    md_Recipeinfo.temp1 = NoWeek.ToString();
                    //md_Recipeinfo.id = new Catering_Rules.RecipeInformation().GetMaxId();
                    int RecipeInformationId = new Catering_Rules.T_RecipeInformation().Add(md_Recipeinfo);

                    //保存食谱详细用量
                    foreach (DataRow rowinfo in dt_RecipesInfo.Select("RandomId='" + dt_Recipes.Rows[i]["RandomId"].ToString() + "'"))
                    {
                        Catering_Model.E_RecipeInformationInfo md_Recipeinfo_Info = new Catering_Model.E_RecipeInformationInfo();
                        md_Recipeinfo_Info.RecipeInformationID = RecipeInformationId;
                        md_Recipeinfo_Info.RawID = Convert.ToInt32(rowinfo["RawID"].ToString());
                        md_Recipeinfo_Info.Number = Convert.ToDecimal(rowinfo["Number"].ToString());
                        new Catering_Rules.T_RecipeInformationInfo().Add(md_Recipeinfo_Info);
                    }
                }
            }
        }

        //获取星期对应的值
        public int GetWeekInt(DayOfWeek week)
        {
            switch (week)
            {
                case DayOfWeek.Monday://星期一
                    return 1;
                    break;
                case DayOfWeek.Tuesday://星期二
                    return 2;
                    break;
                case DayOfWeek.Wednesday://星期三
                    return 3;
                    break;
                case DayOfWeek.Thursday://星期四
                    return 4;
                    break;
                case DayOfWeek.Friday://星期五
                    return 5;
                    break;
                case DayOfWeek.Saturday://星期六
                    return 6;
                    break;
                case DayOfWeek.Sunday://星期日
                    return 0;
                    break;
                default:
                    return -1;
                    break;
            }
        }

        //导入食谱
        protected void but_input_Click(object sender, EventArgs e)
        {
            string CID = this.Hidshipuid.Value;
            if (Request.QueryString["IsNew"] != null)
            {
                CID = Request.QueryString["cid"].ToString();
            }
            Catering_Model.E_Recipes md = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(CID));
            if (md.GroupID != 0)
            {
                Response.Redirect("shippu_regth.aspx?cid=" + CID + "&IsGroupCatering=true&Edit=true");
            }
            else
            {
                Response.Redirect("shippu_regth.aspx?cid=" + CID + "&Edit=true");
            }
        }

        //加载食谱
        protected void but_input_Loadshipu_Click(object sender, EventArgs e)
        {
            //餐别列表
            this.dt_FoodMealType = new Catering_Rules.FoodMealType().GetAllList().Tables[0];
            //生成食谱默认数据
            this.dt_AutoRecipe = new Catering_Rules.AutoRecipe().GetAllList().Tables[0];
            //标准摄入量
            this.LoadSRliang();
            //周期对于日期
            this.WeekBing();

            string Rid = this.Hidshipuid.Value;//食谱ID
            string RecipeInfoDate = this.HidshipuWeek.Value;//导入时间段
            string startTime = RecipeInfoDate.Split('|')[0];
            string endTime = RecipeInfoDate.Split('|')[1];
            string strwhere = "MID=" + Rid + " and Date>=convert(datetime,'" + startTime + "') and Date<=convert(datetime,'" + endTime + "')";
            DataTable dt_RecipeInformation = new Catering_Rules.T_RecipeInformation().GetList(strwhere).Tables[0];

            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            for (int j = 0; j < this.strWeek.Length; j++)
            {
                if (this.WeekDatetime[this.strWeek[j]] != null)
                {
                    int intWeek = this.GetWeekInt(Convert.ToDateTime(this.WeekDatetime[this.strWeek[j]].ToString()).DayOfWeek);
                    foreach (DataRow dt_row in dt_RecipeInformation.Select("Week=" + intWeek))
                    {
                        string strRandomId = Guid.NewGuid().ToString();
                        DataRow row = dt_Recipes.NewRow();
                        row["Date"] = this.WeekDatetime[this.strWeek[j]].ToString();
                        row["CID"] = dt_row["CID"].ToString();
                        row["FMID"] = dt_row["FMID"].ToString();
                        row["RandomID"] = "div_" + strRandomId;
                        dt_Recipes.Rows.Add(row);

                        DataTable dt_RecipeinfoInfo = new Catering_Rules.T_RecipeInformationInfo().GetList("RecipeInformationID=" + dt_row["id"].ToString()).Tables[0];
                        foreach (DataRow rows in dt_RecipeinfoInfo.Rows)
                        {
                            DataRow rowinfo = dt_RecipesInfo.NewRow();
                            rowinfo["RandomID"] = row["RandomID"].ToString();
                            rowinfo["RawID"] = rows["RawID"].ToString();
                            rowinfo["Number"] = rows["Number"].ToString();
                            dt_RecipesInfo.Rows.Add(rowinfo);
                        }
                    }
                }
            }
            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;
        }

        //更换周期
        protected void Dr_zhoulist_SelectedIndexChanged(object sender, EventArgs e)
        {
            //保存本周食谱信息
            if (this.HidWeekValue.Value != this.Dr_zhoulist.SelectedValue)
            {
                this.Save_Recipes();
                this.HidWeekValue.Value = this.Dr_zhoulist.SelectedValue;
            }

            Catering_Model.E_RecipesWeek md_Week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.Dr_zhoulist.SelectedValue));
            this.WeekBing();
            this.lblzhouqi.Text = md_Week.startDate.ToShortDateString() + "至" + md_Week.endDate.ToShortDateString();
            this.LoadData();
            this.LoadSRliang();


        }

        //加载标准摄入量总和
        public void LoadSRliang()
        {
            ArrayList al_sheruliang = new ArrayList();
            decimal[] bl_Num = new decimal[24]; //存放最后的标量值

            if (Request.QueryString["cid"] != null)
            {
                StringBuilder sb = new StringBuilder();//标量值查询条件
                sb.Append("1=2");

                string RecipesID = Request.QueryString["cid"].ToString();
                Catering_Model.E_Recipes md_shipu = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(RecipesID));

                DataTable dt_CateringGroupInfo = new DataTable();
                if (Request.QueryString["IsGroupCatering"] != null)//群体配餐
                {
                    dt_CateringGroupInfo = new Catering_Rules.CateringGroupInfo().GetNETypes(md_shipu.GroupID).Tables[0];
                }
                else
                {
                    dt_CateringGroupInfo = new Catering_Rules.CateringGroupInfo().GetNETypes(md_shipu.PID.ToString()).Tables[0];
                }

                if (dt_CateringGroupInfo != null && dt_CateringGroupInfo.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_CateringGroupInfo.Rows)
                    {
                        string Group_tedianId = row["Group_tedianID"].ToString(); //适合人群
                        string SexId = row["SexID"].ToString();//性别
                        string AgeId = row["OldAreaID"].ToString();//年龄段
                        string LaborGradeId = row["LaborGradeID"].ToString();//劳动级别
                        string strwhere = "SexID=" + SexId + " and OldAreaID=" + AgeId + " and LaborGradeID=" + LaborGradeId + " and Group_tedianID=" + Group_tedianId;
                        sb.Append(" or (" + strwhere + ")");
                    }

                    //计算标量值
                    DataTable dt_Ingestion = new Catering_Rules.Ingestion().GetList(sb.ToString()).Tables[0];
                    foreach (DataRow row in dt_Ingestion.Rows)
                    {
                        bl_Num[Convert.ToInt32(row["NutritionElementsID"]) - 1] += Convert.ToDecimal(row["Number"]);
                    }

                    for (int i = 0; i < 24; i++)
                    {
                        al_sheruliang.Add(Convert.ToDouble(bl_Num[i]) / dt_CateringGroupInfo.Rows.Count);
                    }
                }
            }
            Session["al_sheruliang"] = al_sheruliang;
        }

        //获取标准摄入量
        public string GetSRliang(string index)
        {
            if (this.Dr_zhoulist.SelectedItem == null)
                return "0";

            ArrayList al_sheruliang = (ArrayList)Session["al_sheruliang"];
            Catering_Model.E_RecipesWeek md_week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.Dr_zhoulist.SelectedValue));
            int DayCount = (md_week.endDate - md_week.startDate).Days + 1;//提取本周天数
            return (Convert.ToDouble(al_sheruliang[Convert.ToInt32(index) - 1]) * DayCount).ToString();
        }

        //获取实际摄入量以及周平均值
        protected void But_GetEMAll_Click(object sender, EventArgs e)
        {
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            DataTable dt_FoodMealType = new Catering_Rules.FoodMealType().GetList("1=1 order by temp1").Tables[0];

            string str = this.Hid_GetEMAll.Value;
            string strDate = str.Split('|')[0].ToString();
            string WeekID = str.Split('|')[1].ToString();
            string FoodID = str.Split('|')[2].ToString();

            ArrayList al = new ArrayList();
            string strSRLBZ = "";
            string strWeekPJList = "";//周平均
            string strDayList = "";//天含量
            string strTypeList = "";//食物分类统计
            double[] iSRLNum = new double[24];
            double[] iNum = new double[24]; //周平均
            double[] iDayNum = new double[24];//天含量

            string strjinji = "";//经济评价
            string strjinjiSum = "";
            string stranquan = "";//安全提示

            ArrayList al_sheruliang = (ArrayList)HttpContext.Current.Session["al_sheruliang"];

            #region 获取标准摄入量
            if (al_sheruliang != null && al_sheruliang.Count > 0)
            {
                for (int i = 0; i < 24; i++)
                {
                    iSRLNum[i] = Convert.ToDouble(al_sheruliang[i]);
                }

                if (FoodID == "-1")
                {
                    for (int i = 0; i < 24; i++)
                    {
                        strSRLBZ += iSRLNum[i].ToString() + ",";
                    }
                }
                else
                {
                    string strFMName = new Catering_Rules.FoodMealType().GetModel(Convert.ToInt32(FoodID)).FMName;
                    if (strFMName == "早餐" || strFMName == "晚餐")
                    {
                        for (int i = 0; i < 24; i++)
                        {
                            strSRLBZ += ((iSRLNum[i]) / 10 * 3).ToString() + ",";
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 24; i++)
                        {
                            strSRLBZ += ((iSRLNum[i]) / 10 * 4).ToString() + ",";
                        }
                    }
                }

            }
            else
            {
                for (int i = 0; i < 24; i++)
                {
                    strSRLBZ += "0" + ",";
                }
            }
            #endregion

            #region 计算摄入量以及平均值
            if (dt_Recipes != null && dt_Recipes.Rows.Count > 0)
            {
                //计算当日营养量
                string strwhere = "Date='" + strDate + "' and ";
                string where = "";
                if (FoodID == "-1")
                {
                    where = "1=1";
                }
                else if (dt_FoodMealType.Select("id=" + FoodID)[0]["FMName"].ToString() == "午餐")
                {
                    string strswcid = dt_FoodMealType.Select("FMName='上午茶'")[0]["id"].ToString();
                    where = "(FMID='" + FoodID + "' or FMID='" + strswcid + "')";
                }
                else if (dt_FoodMealType.Select("id=" + FoodID)[0]["FMName"].ToString() == "晚餐")
                {
                    string strxwcid = dt_FoodMealType.Select("FMName='下午茶'")[0]["id"].ToString();
                    where = "(FMID='" + FoodID + "' or FMID='" + strxwcid + "')";
                }
                else
                {
                    where = "FMID='" + FoodID + "'";
                }

                //strwhere = "Date='" + strDate + "'" + (FoodID == "-1" ? "" : (" and FMID='" + FoodID + "'"));
                strwhere = strwhere + where;
                if (dt_Recipes.Select(strwhere).Count() > 0)//判定是否有菜
                {
                    foreach (DataRow row in dt_Recipes.Select(strwhere))
                    {
                        //通过原料热量进行计算
                        foreach (DataRow rowinfo in dt_RecipesInfo.Select("RandomID='" + row["RandomID"].ToString() + "'"))
                        {
                            DataTable dt_NutrientComposition = new Catering_Rules.NutrientComposition().GetList(24, "RawID=" + rowinfo["RawID"], "NutritionElementsID").Tables[0];
                            for (int i = 0; i < dt_NutrientComposition.Rows.Count; i++)
                            {
                                string NC_Content = dt_NutrientComposition.Rows[i]["Content"].ToString() == "" ? "0" : dt_NutrientComposition.Rows[i]["Content"].ToString();
                                iDayNum[i] += Convert.ToDouble(NC_Content) / 100 * Convert.ToDouble(rowinfo["Number"].ToString());
                            }
                        }

                        /*//通过菜热量进行计算
                        DataTable dt_DishNutrien = new Catering_Rules.DishNutrien().GetList(24, "Dishid=" + row["CID"].ToString(), "Convert(int,fatherid)").Tables[0];
                        for (int i = 0; i < dt_DishNutrien.Rows.Count; i++)
                        {
                            iDayNum[i] += Convert.ToDouble(dt_DishNutrien.Rows[i]["Content"].ToString());
                        }
                        */
                    }
                    for (int i = 0; i < iDayNum.Length; i++)
                    {
                        strDayList += iDayNum[i].ToString() + ",";
                    }

                }
                else
                {
                    for (int i = 0; i < 24; i++)
                    {
                        strDayList += "0" + ",";
                    }
                }

                //计算本周平均营养量
                string strWeekwhere = where;//(FoodID == "-1" ? "" : ("FMID='" + FoodID + "'"));
                foreach (DataRow rows in dt_Recipes.Select(strWeekwhere))
                {
                    //通过原料热量进行计算
                    foreach (DataRow rowinfo in dt_RecipesInfo.Select("RandomID='" + rows["RandomID"].ToString() + "'"))
                    {
                        DataTable dt_NutrientComposition = new Catering_Rules.NutrientComposition().GetList(24, "RawID=" + rowinfo["RawID"], "NutritionElementsID").Tables[0];
                        for (int i = 0; i < dt_NutrientComposition.Rows.Count; i++)
                        {
                            string NC_Content = dt_NutrientComposition.Rows[i]["Content"].ToString() == "" ? "0" : dt_NutrientComposition.Rows[i]["Content"].ToString();
                            iNum[i] += Convert.ToDouble(NC_Content) / 100 * Convert.ToDouble(rowinfo["Number"].ToString());
                        }
                    }
                    /*
                    DataTable dt_DishNutrien = new Catering_Rules.DishNutrien().GetList(24, "Dishid=" + rows["CID"].ToString(), "Convert(int,fatherid)").Tables[0];
                    for (int i = 0; i < dt_DishNutrien.Rows.Count; i++)
                    {
                        iNum[i] += Convert.ToDouble(dt_DishNutrien.Rows[i]["Content"].ToString());
                    }
                    */
                }

                Catering_Model.E_RecipesWeek md = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(WeekID));
                m_Daycount = (md.endDate - md.startDate).Days + 1;
                for (int i = 0; i < iNum.Length; i++)
                {
                    strWeekPJList += (iNum[i] / m_Daycount).ToString() + ",";
                }

            }
            else
            {
                for (int i = 0; i < 24; i++)
                {
                    strWeekPJList += "0" + ",";
                    strDayList += "0" + ",";
                }
            }
            #endregion

            #region 获取安全提示以及经济评价
            if (dt_Recipes != null && dt_Recipes.Rows.Count > 0)
            {
                string strRawIDList = "";//不重复的原料ID
                decimal DishPiceSum = 0;
                foreach (DataRow row in dt_Recipes.Select("Date='" + strDate + "'"))
                {
                    Catering_Model.E_Dish md = new Catering_Rules.T_Dish().GetModel(Convert.ToInt32(row["CID"].ToString()));
                    //stranquan += md.Name + ":" + md.Back + "；";
                    decimal DishPice = 0;
                    foreach (DataRow rowinfo in dt_RecipesInfo.Select("RandomID='" + row["RandomID"].ToString() + "'"))
                    {
                        #region 计算经济评价
                        int RawID = Convert.ToInt32(rowinfo["RawID"].ToString());
                        decimal Number = Convert.ToDecimal(rowinfo["Number"].ToString());

                        Catering_Model.E_Recipes md_Recipes = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(Request.QueryString["cid"].ToString()));
                        int PID_ClassID = 0;
                        if (md_Recipes.PID != 0)//个人配餐
                        {
                            PID_ClassID = Convert.ToInt32(HttpContext.Current.Session["ClassID"].ToString());
                        }
                        else//群体配餐
                        {
                            PID_ClassID = md_Recipes.ClassIDs;
                        }
                        DataTable dt_in = new Catering_Rules.InDbInfo().GetList(1, "ClassID=" + PID_ClassID + "and RAWID=" + RawID, "IntDate desc").Tables[0];
                        if (dt_in != null && dt_in.Rows.Count > 0)
                        {
                            try
                            {
                                //单位换算
                                Catering_Model.E_RawMaterial md_RawMaterial = new Catering_Rules.T_RawMaterial().GetModel(RawID);
                                int UnitID = Convert.ToInt32(md_RawMaterial.temp2);//入库单位ID
                                Catering_Model.Units units = new Catering_Rules.Units().GetModel(UnitID);

                                bool iskg = true;
                                decimal guige = 1;
                                decimal UtilKg = Toolss.GetSpecifications(RawID, units.UName, out iskg);
                                guige = iskg ? 1000 : 1;
                                decimal price = new Catering_Rules.BalanceInfo().GetPriceByRawID(PID_ClassID, RawID.ToString(), DateTime.Now);
                                DishPice += Toolss.GetMathResult(price / (UtilKg * guige) * Number, 2, 3);
                            }
                            catch { }
                        }
                        #endregion

                        if (strRawIDList.IndexOf(rowinfo["RawID"].ToString() + ",") < 0)
                        {
                            strRawIDList += rowinfo["RawID"].ToString() + ",";
                        }
                    }
                    DishPiceSum += DishPice;
                    strjinji += md.Name + ":" + decimal.Round(DishPice, 2).ToString() + "；";
                }
                if (strRawIDList.Length > 1)
                {
                    DataTable dt_RawByListID = new Catering_Rules.T_RawMaterial().GetList("id in (" + strRawIDList.TrimEnd(',') + ")").Tables[0];
                    foreach (DataRow row_RawByID in dt_RawByListID.Rows)
                    {
                        if (row_RawByID["SafetyTips"] != null && row_RawByID["SafetyTips"].ToString() != "")
                        {
                            stranquan += row_RawByID["RAWName"].ToString() + ":" + row_RawByID["SafetyTips"].ToString() + "；";
                        }
                    }

                    strjinjiSum += "总价:" + decimal.Round(DishPiceSum, 2).ToString() + "；" + strjinji;
                }
                else
                {
                    strjinjiSum = "";
                }
            }
            else
            {
                strjinji = "";
                strjinjiSum = "";
                stranquan = "";
            }
            #endregion

            #region 食物分类统计
            DataTable dt_RawMaterialsType = new Catering_Rules.RawMaterialsType().GetAllList().Tables[0];
            if (dt_RawMaterialsType != null && dt_RawMaterialsType.Rows.Count > 0)
            {
                foreach (DataRow rowRawType in dt_RawMaterialsType.Rows)
                {
                    double d_Count = 0;
                    foreach (DataRow rowinfo in dt_RecipesInfo.Select("RAWZS='" + rowRawType["id"].ToString() + "'"))
                    {
                        d_Count += Convert.ToDouble(rowinfo["Number"].ToString());
                    }
                    if (d_Count > 0 && m_Daycount > 0) d_Count = d_Count / Convert.ToDouble(m_Daycount);
                    strTypeList += rowRawType["id"].ToString() + "|" + d_Count.ToString("0.00") + ",";
                }
            }
            #endregion

            al.Add(strWeekPJList.TrimEnd(','));
            al.Add(strDayList.TrimEnd(','));
            al.Add(strSRLBZ.TrimEnd(','));
            al.Add(strjinjiSum);
            al.Add(stranquan);
            al.Add(strTypeList.Trim(','));

            ScriptManager.RegisterStartupScript(
                this.UpdatePanel1,
                this.UpdatePanel1.GetType(),
                Guid.NewGuid().ToString(),
                "$(document).ready(function () {fu_LoadENAll('" + al[0].ToString() + "','" + al[1].ToString() + "','" + al[2].ToString() + "','" + al[3].ToString() + "','" + al[4].ToString() + "','" + al[5].ToString() + "');});",
                true);
        }

        //自动生成食谱
        protected void But_AutoGenerate_Click(object sender, EventArgs e)
        {
            string strType = this.Hid_AutoGenerate.Value;

            //主食和副食设置列表
            //MainDID=1:主食,MainDID=2:副食，此主食与dishtype表的主食是不同的概念
            DataTable dt_MainDeputyAuto = new Catering_Rules.MainDeputyAuto().GetAllList().Tables[0];
            string RawTypeZhu = "";//主食种属（原料种属RawMaterialsType表ID列）
            string RawTypeFu = ""; //副食种属（原料种属RawMaterialsType表ID列）
            foreach (DataRow row in dt_MainDeputyAuto.Rows)
            {
                if (row["MainDID"].ToString() == "1")
                {
                    RawTypeZhu += row["RawMaterialsTypeID"].ToString() + ",";
                }
                else
                {
                    RawTypeFu += row["RawMaterialsTypeID"].ToString() + ",";
                }
            }

            if (RawTypeZhu == "" || RawTypeFu == "")
            {
                ScriptManager.RegisterStartupScript(
                this.UpdatePanel1,
                this.UpdatePanel1.GetType(),
                Guid.NewGuid().ToString(),
                "$(document).ready(function () {fu_zd_submit('NOType');});", true);
                return;
            }

            DataTable dt_FoodMealType = new Catering_Rules.FoodMealType().GetAllList().Tables[0];
            this.WeekBing();
            foreach (string strweek in strWeek)
            {
                if (WeekDatetime[strweek] != null)
                {
                    foreach (DataRow row in dt_FoodMealType.Rows)
                    {
                        if (row["FMName"].ToString() == "上午茶" || row["FMName"].ToString() == "下午茶")
                            continue;

                        int BL = 4;
                        ArrayList al = new ArrayList();//对应餐别的类别列表
                        string[] typelist = strType.TrimEnd(',').Split(',');
                        foreach (string str in typelist)
                        {
                            if (str.Split('|')[0] == row["id"].ToString())
                            {
                                al.Add(str);//获取对应餐别菜品类别的配置参数
                            }
                        }
                        if (row["FMName"].ToString() == "早餐" || row["FMName"].ToString() == "晚餐")
                        {
                            BL = 3;
                        }
                        LoadAutoType(al, RawTypeZhu, RawTypeFu, BL, row["id"].ToString(), WeekDatetime[strweek].ToString());
                    }
                }
            }
            ScriptManager.RegisterStartupScript(
                this.UpdatePanel1,
                this.UpdatePanel1.GetType(),
                Guid.NewGuid().ToString(),
                "$(document).ready(function () {fu_zd_submit('OK');});", true);
            return;
        }

        /// <summary>
        /// 根据参数自动生成菜品（生成当周某天某餐别的菜品）
        /// </summary>
        /// <param name="al">对应餐别菜品类别的配置参数</param>
        /// <param name="RawTypeZhu">@主食种属</param>
        /// <param name="RawTypeFu">@副食种属</param>
        /// <param name="FoodBL">餐别比例（早餐：3，午餐：4，晚餐：3，夜餐：4）</param>
        /// <param name="FoodID">餐别ID（早餐、午餐、晚餐、夜餐）</param>
        /// <param name="Datetime">日期</param>
        public void LoadAutoType(ArrayList al, string RawTypeZhu, string RawTypeFu, decimal FoodBL, string FoodID, string Datetime)
        {
            int zsTypeID = -1;//得到DishType表DT=“主食”这个类别的ID
            ArrayList al_sheruliang = (ArrayList)HttpContext.Current.Session["al_sheruliang"];//标准摄入量
            DataTable dt_DishType = new Catering_Rules.DishType().GetList("DT='主食'").Tables[0];
            if (dt_DishType != null && dt_DishType.Rows.Count > 0)
            {
                zsTypeID = Convert.ToInt32(dt_DishType.Rows[0]["id"].ToString());
            }

            //区分主食和菜类别
            ArrayList al_zhushi = new ArrayList();//该餐别（早餐、午餐、晚餐、夜餐）配置参数为主食（DishType表DT=“主食”）的配置参数列表
            ArrayList al_cai = new ArrayList();   //该餐别（早餐、午餐、晚餐、夜餐）配置参数为非主食（DishType表DT=“主食”）的配置参数列表
            foreach (string str in al)
            {
                if (Convert.ToInt32(str.Split('|')[1]) == zsTypeID)
                    al_zhushi.Add(str);
                else
                    al_cai.Add(str);
            }
            decimal SumReL = Convert.ToDecimal(al_sheruliang[0]);//此食谱各元素标准量摄入量总和的总热量(kcal)
            //按照比例蛋白质：15% 脂肪：25% 碳水化合物：60%
            decimal SumDBZ = SumReL * 15 / 100 / 4;//蛋白质的质量(g)
            decimal SumZF = SumReL * 25 / 100 / 9;//脂肪的质量(g)
            decimal SumTSHHW = SumReL * 60 / 100 / 4;//碳水化合物质量(g)

            //计算早餐个元素用量
            decimal SumDBZ_zao = SumReL * 15 / 100 / 4 / 10 * FoodBL;//蛋白质的质量(g)
            decimal SumZF_zao = SumReL * 25 / 100 / 9 / 10 * FoodBL;//脂肪的质量(g)
            decimal SumTSHHW_zao = SumReL * 60 / 100 / 4 / 10 * FoodBL;//碳水化合物质量(g)

            //判定该餐别（早餐、午餐、晚餐、夜餐）配置参数是否存在主食（DishType表DT=“主食”）
            if (al_zhushi.Count > 0)
            {
                AutoByZhuFu(RawTypeZhu, al_zhushi, SumTSHHW_zao, true, Datetime);
            }

            //主食中蛋白质含量
            decimal SumDBZtemp = GetDBZNumber(FoodID, Datetime);
            while ((SumDBZ_zao - SumDBZtemp) < 0)
            {
                DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
                DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

                foreach (DataRow row in dt_Recipes.Select("FMID='" + FoodID + "' and Date='" + Datetime + "'"))
                {
                    while (dt_RecipesInfo.Select("RandomID='" + row["RandomID"].ToString() + "'").Count() > 0)
                    {
                        dt_RecipesInfo.Select("RandomID='" + row["RandomID"].ToString() + "'")[0].Delete();
                    }
                }
                while (dt_Recipes.Select("FMID='" + FoodID + "' and Date='" + Datetime + "'").Count() > 0)
                {
                    dt_Recipes.Select("FMID='" + FoodID + "' and Date='" + Datetime + "'")[0].Delete();
                }

                ViewState["dt_Recipes"] = dt_Recipes;
                ViewState["dt_RecipesInfo"] = dt_RecipesInfo;

                //判定是否存在主食
                if (al_zhushi.Count > 0)
                {
                    AutoByZhuFu(RawTypeZhu, al_zhushi, SumTSHHW_zao, true, Datetime);
                }
                SumDBZtemp = GetDBZNumber(FoodID, Datetime);
            }

            //判断是否存在菜
            if (al_cai.Count > 0)
            {
                AutoByZhuFu(RawTypeFu, al_cai, SumDBZ_zao - SumDBZtemp, false, Datetime);
            }
        }

        //计算蛋白质含量
        public decimal GetDBZNumber(string FoodID, string Datetime)
        {
            //计算对应主食中含有的蛋白质
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            decimal SumDBZtemp = 0;
            foreach (DataRow row in dt_Recipes.Select("FMID='" + FoodID + "' and Date='" + Datetime + "'"))
            {
                foreach (DataRow rowinfo in dt_RecipesInfo.Select("RandomID='" + row["RandomID"].ToString() + "'"))
                {
                    int RawID = Convert.ToInt32(rowinfo["RawID"].ToString());
                    DataTable dt_NutrientComposition = new Catering_Rules.NutrientComposition().GetList("RawID=" + RawID + " and NutritionElementsID=2").Tables[0];
                    decimal BZDBZNumber = Convert.ToDecimal(dt_NutrientComposition.Rows[0]["Content"].ToString() == "" ? "0" : dt_NutrientComposition.Rows[0]["Content"].ToString());//100g该原料对应的蛋白质量
                    SumDBZtemp += BZDBZNumber / 100 * Convert.ToDecimal(rowinfo["Number"].ToString());
                }
            }
            return SumDBZtemp;
        }

        /// <summary>
        /// 随机生成食谱
        /// </summary>
        /// <param name="RawType">@主食种属、@副食种属</param>
        /// <param name="al_TypeList">该餐别（早餐、午餐、晚餐、夜餐）配置参数为主食（DishType表DT=“主食”）获取非主食（DishType表DT!=“主食”）的配置参数列表</param>
        /// <param name="SumZL">早餐碳水化合物质量(g)元素用量</param>
        /// <param name="IsZhu">是否为主食（DishType表DT=“主食”）</param>
        /// <param name="Datetime">日期</param>
        public void AutoByZhuFu(string RawType, ArrayList al_TypeList, decimal SumZL, bool IsZhu, string Datetime)
        {
            ArrayList al_CaiList = new ArrayList();
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            string strRawIDList = "";//得到种属为（@主食种属/@副食种属）的原料
            DataTable dt_RawMaterial = new Catering_Rules.T_RawMaterial().GetList("RAWZS in(" + RawType.TrimEnd(',') + ")").Tables[0];
            foreach (DataRow row in dt_RawMaterial.Rows)
            {
                strRawIDList += row["id"].ToString() + ",";
            }


            string strDishIDList = "";//得到含有种属为（@主食种属/@副食种属）的原料的菜详细表（DishInfo）的DID即Dish表的ID
            DataTable dt_DishID = new Catering_Rules.T_DishInfo().GetDishID(strRawIDList.TrimEnd(',')).Tables[0];
            foreach (DataRow row in dt_DishID.Rows)
            {
                strDishIDList += row["DID"].ToString() + ",";
            }

            #region 随机出对应的类别的菜（主食:DishType表DT=“主食”）

            foreach (string str in al_TypeList)
            {
                int caiNumber = Convert.ToInt32(str.Split('|')[3]);//配餐参数数量：Number，意为多少道菜
                string strtypeid = "";//配餐参数细类：TypeInfoID，意为DishTypes表ID
                if (str.Split('|')[2] != "-1")//有细类(TypeInfoID)
                {
                    strtypeid += str.Split('|')[2] + ",";
                }
                else
                {
                    DataTable dt_DishTypeInfo = new Catering_Rules.DishTypes().GetList("DTID=" + str.Split('|')[1]).Tables[0];
                    foreach (DataRow row in dt_DishTypeInfo.Rows)
                    {
                        strtypeid += row["id"].ToString() + ",";
                    }
                }
                string getdishwhere = "DTID in (" + strtypeid.TrimEnd(',') + ")";
                if (strDishIDList != "")
                {
                    getdishwhere += " and id in (" + strDishIDList.TrimEnd(',') + ")";
                }
                //获取此餐别参数细类为TypeInfoID并且含有种属为（@主食种属/@副食种属）的原料的菜品的列表
                DataTable dt_caiByTypeInfo = new Catering_Rules.T_Dish().GetList(getdishwhere).Tables[0];
                if (dt_caiByTypeInfo != null && dt_caiByTypeInfo.Rows.Count > 0)
                {
                    if (caiNumber > dt_caiByTypeInfo.Rows.Count)//配置参数的数量>菜品的数量
                    {
                        foreach (DataRow row in dt_caiByTypeInfo.Rows)
                        {
                            DataTable dt_dishInfo = new Catering_Rules.T_DishInfo().GetList("DID=" + row["id"].ToString() + " and Content=0").Tables[0];
                            if (dt_dishInfo != null && dt_dishInfo.Rows.Count > 0)
                                continue;

                            al_CaiList.Add(row["id"].ToString());
                        }
                    }
                    else
                    {
                        ArrayList strIDList = GetRandomIDByNumber(dt_caiByTypeInfo, caiNumber);
                        foreach (string strID in strIDList)
                        {
                            DataTable dt_dishInfo = new Catering_Rules.T_DishInfo().GetList("DID=" + strID + " and Content=0").Tables[0];
                            if (dt_dishInfo != null && dt_dishInfo.Rows.Count > 0)
                                continue;

                            al_CaiList.Add(strID);
                        }
                    }
                }
            }
            #endregion

            //计算出平均每道菜的碳水化合物的量(g)
            if (al_CaiList.Count == 0)
                return;
            decimal PJ_SumTSHHW_zao = SumZL / al_CaiList.Count;//早餐标准碳水化合物的总量(g)/菜的数量

            #region 计算每道菜的原料用量
            foreach (string DishID in al_CaiList)
            {
                DataTable dt_DishInfo = new Catering_Rules.T_DishInfo().GetList("DID=" + DishID).Tables[0];

                int syRawID = -1;//符合需求的原料
                decimal BZNumber = 0;//标准用量
                decimal Numbertemp = 0;//该原料100g 含有的蛋白质或碳水化合物的量
                foreach (DataRow row in dt_DishInfo.Rows)
                {
                    if (strRawIDList.IndexOf(row["RawID"].ToString() + ",") > -1)
                    {
                        syRawID = Convert.ToInt32(row["RawID"].ToString());
                        BZNumber = Convert.ToDecimal(row["Content"].ToString());
                        int NutritionElementsID = (IsZhu ? 4 : 2);
                        DataTable dt_NutrientComposition = new Catering_Rules.NutrientComposition().GetList("RawID=" + syRawID + " and NutritionElementsID=" + NutritionElementsID).Tables[0];
                        Numbertemp = Convert.ToDecimal(dt_NutrientComposition.Rows[0]["Content"].ToString() == "" ? "0" : dt_NutrientComposition.Rows[0]["Content"].ToString());
                    }
                }

                decimal NumberXY = 0;
                decimal NumberBL = 0;
                if (Numbertemp != 0)
                {
                    NumberXY = PJ_SumTSHHW_zao / Numbertemp * 100;//需要量
                    NumberBL = NumberXY / BZNumber;//原料用量比例
                }

                //添加菜与原料
                string RandomId = "div_" + Guid.NewGuid().ToString();
                DataRow row_Dish = dt_Recipes.NewRow();
                row_Dish["Date"] = Datetime;
                row_Dish["CID"] = DishID;
                row_Dish["FMID"] = al_TypeList[0].ToString().Split('|')[0];
                row_Dish["RandomID"] = RandomId;
                dt_Recipes.Rows.Add(row_Dish);

                //需要保存菜用量详细
                foreach (DataRow rows in dt_DishInfo.Rows)
                {
                    DataRow rowinfo = dt_RecipesInfo.NewRow();
                    rowinfo["RandomID"] = RandomId;
                    rowinfo["RawID"] = rows["RawID"].ToString();
                    rowinfo["Number"] = decimal.Round(Convert.ToDecimal(rows["Content"].ToString()) * NumberBL, 2);
                    dt_RecipesInfo.Rows.Add(rowinfo);
                }
            }
            #endregion

            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;
        }

        //随机获取对应ID
        public ArrayList GetRandomIDByNumber(DataTable dt, int Number)
        {
            int rowcount = dt.Rows.Count;
            string strID = "";
            ArrayList al = new ArrayList();
            for (int i = 0; i < Number; i++)
            {
                Random rd = new Random();
                int index = rd.Next(0, rowcount - 1);
                string id = "";
                if (strID == "")
                {
                    id = dt.Select()[index]["id"].ToString();
                }
                else
                {
                    id = dt.Select("id not in (" + strID.TrimEnd(',') + ")")[index]["id"].ToString();
                }
                rowcount -= 1;
                strID += id + ",";
                al.Add(id);
            }
            return al;
        }

        //通过食谱ID 获取周期
        public string GetZhouOptionByRid(string Rid)
        {
            DataTable dt_Week = new Catering_Rules.T_RecipesWeek().GetList("RecipesID=" + Rid.ToString() + " order by Number").Tables[0];
            StringBuilder sb = new StringBuilder();
            if (dt_Week != null && dt_Week.Rows.Count > 0)
            {
                foreach (DataRow row in dt_Week.Rows)
                {
                    string startTime = Convert.ToDateTime(row["startDate"].ToString()).ToShortDateString();
                    string endTime = Convert.ToDateTime(row["endDate"].ToString()).ToShortDateString();
                    sb.Append("<option value=\"" + startTime + "|" + endTime + "\">" + row["temp1"].ToString() + "</option>");
                }
            }
            return sb.ToString();
        }

        //导出食谱Excel
        protected void but_Excel_Click(object sender, EventArgs e)
        {
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];

            DataSet ds = new DataSet();
            dt_Recipes.TableName = "Recipes";
            dt_RecipesInfo.TableName = "RecipesInfo";
            ds.Tables.Add(dt_Recipes.Copy());
            ds.Tables.Add(dt_RecipesInfo.Copy());

            string fileName = Guid.NewGuid().ToString() + ".xls";
            string path = Server.MapPath("../../" + Catering_DBOpertion.PubConstant.GetConfigValue("TempExcel") + "/" + fileName);
            bool success = Catering.View_Operaction.DataSetToExcelHelper.DataSetToExcel(ds, path, false);

            if (!success)
                throw new Exception("Excel导出失败！");

            this.Response.AppendHeader("Content-Disposition", "attachment;filename=" + this.Server.UrlEncode(fileName));
            this.Response.ContentType = "application/ms-excel";

            System.IO.FileInfo file = new System.IO.FileInfo(path);
            long length = file.Length;

            Dictionary<int, int> fileDic = new Dictionary<int, int>();
            this.LoadDictionary(length, 1024, fileDic);

            for (int i = 0; i < fileDic.Count; i++)
            {
                int count = fileDic[i + 1];
                byte[] bytes = new byte[count];

                using (System.IO.FileStream fileStream = System.IO.File.OpenRead(path))
                {
                    fileStream.Seek(i * 1024, System.IO.SeekOrigin.Begin);
                    fileStream.Read(bytes, 0, bytes.Length);
                }

                this.Response.OutputStream.Write(bytes, 0, bytes.Length);
                this.Response.Flush();
            }
            this.Response.Close();

            System.IO.File.Delete(path);
        }

        private void LoadDictionary(long p, int blockMaxSize, Dictionary<int, int> dic)
        {
            if (p - blockMaxSize > 0)
            {
                dic.Add(dic.Count + 1, blockMaxSize);
                this.LoadDictionary(p - blockMaxSize, blockMaxSize, dic);
            }
            else if (p - blockMaxSize == 0)
            {
                dic.Add(dic.Count + 1, blockMaxSize);
                return;
            }
            else
            {
                dic.Add(dic.Count + 1, Int32.Parse(p.ToString()));
                return;
            }

        }

        //导入食谱Excel
        protected void But_ExcelImp_Click(object sender, EventArgs e)
        {
            DataTable dt_Recipes = (DataTable)ViewState["dt_Recipes"];
            DataTable dt_RecipesInfo = (DataTable)ViewState["dt_RecipesInfo"];
            if (Request.QueryString["cid"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('请先选择食谱!')", true);
                return;
            }

            string path = new DataBase_Manage_Operaction().UpFile(this.file_Excel);
            DataSet ds = Catering.View_Operaction.DataSetToExcelHelper.ExcelToDataSet(path);

            if (ds != null && ds.Tables.Count > 1)
            {
                this.Dr_zhoulist_SelectedIndexChanged(null, null);
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    if (!this.WeekDatetime.ContainsValue(Convert.ToDateTime(r["Date"]).ToShortDateString()))
                        continue;

                    DataRow row = dt_Recipes.NewRow();
                    row["Date"] = Convert.ToDateTime(r["Date"]).ToShortDateString();
                    row["CID"] = r["CID"];
                    row["FMID"] = r["FMID"];
                    row["RandomID"] = r["RandomID"];
                    dt_Recipes.Rows.Add(row);

                    foreach (DataRow rinfo in ds.Tables[1].Select("RandomID='" + row["RandomID"].ToString() + "'"))
                    {
                        DataRow rowinfo = dt_RecipesInfo.NewRow();
                        rowinfo["RandomID"] = rinfo["RandomID"].ToString();
                        rowinfo["RawID"] = rinfo["RawID"].ToString();
                        rowinfo["Number"] = rinfo["Number"].ToString();
                        dt_RecipesInfo.Rows.Add(rowinfo);
                    }
                }
            }
            ViewState["dt_Recipes"] = dt_Recipes;
            ViewState["dt_RecipesInfo"] = dt_RecipesInfo;

        }
    }
}